<template>
  <el-dialog
    title="修改用户信息"
    :visible.sync="isShowDialog"
    width="50%"
    @close="editDialogClosed"
  >
    <el-form
      :model="editForm"
      :rules="editFormRules"
      ref="editFormRef"
      label-width="70px"
    >
      <el-form-item label="用户名">
        <el-input v-model="editForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="editForm.mobile"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="$store.commit('change', false)">取 消</el-button>
      <el-button type="primary" @click="editUserInfo()">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { mapState } from 'vuex'
var checkEmail = (rule, value, cb) => {
  const regEmail = /^\w+@\w+(\.\w+)+$/
  if (regEmail.test(value)) {
    return cb()
  }

  cb(new Error('请输入合法的邮箱'))
}
var checkMobile = (rule, value, cb) => {
  const regMobile = /^1[34578]\d{9}$/
  if (regMobile.test(value)) {
    return cb()
  }

  cb(new Error('请输入合法的手机号码'))
}
export default {
  methods: {
    editDialogClosed() {
      this.$store.commit('change', false)
      this.$refs.editFormRef.resetFields()
    },
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写完整用户信息')
        }

        const { data } = await this.$http.put(
          'users/' + this.editForm.id,
          this.editForm
        )
        if (data.meta.status !== 200) {
          return this.$message.error('更改用户信息失败')
        }
        this.$message.success('更改用户信息成功')
        this.$store.commit('change', false)
        this.$emit('getList')
      })
    }
  },
  data() {
    return {
      isShowDialog: false,
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            message: '邮箱格式不正确，请重新输入',
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: checkMobile,
            message: '手机号码不正确，请重新输入',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    ...mapState(['editDialogVisible', 'editForm'])
  },
  watch: {
    editDialogVisible: {
      handler(newVal) {
        this.isShowDialog = newVal
      }
    }
  }
}
</script>
<style lang="less" scoped></style>
